<template>
  <div class="enterpriseMonitoringList">
    <PageTitle :goBack="false" title="企业监控列表" :border="true" />
    <div class="myCardCss" style="width: 100%">
      <a-form class="myForm1" :model="formData">
        <a-form-item label="风险动态时间">
          <a-radio-group name="radioGroup" v-model:value="formData.time" @change="changeTime">
            <a-radio :value="1">今天</a-radio>
            <a-radio :value="2">近三天</a-radio>
            <a-radio :value="3">近一周</a-radio>
            <a-radio :value="4">近半月</a-radio>
            <a-radio :value="5">近一个月</a-radio>
            <a-radio :value="0">自定义日期</a-radio>
          </a-radio-group>
          <a-range-picker
            v-if="formData.time === 0"
            v-model:value="formData.times"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-item>
        <a-button
          type="primary"
          danger
          @click="changeTime"
          style="margin-left: 106px; border-radius: 4px"
          >查询</a-button
        >
        <a-button @click="resetData" style="border-radius: 4px; margin-left: 12px">重置</a-button>
      </a-form>
    </div>
    <div class="myCardCss" style="width: 100%; margin-top: 8px">
      <div class="addBtn">
        <div class="btnItem" @click="addCompany">添加企业</div>
        <div class="btnItem" @click="openUpload">批量监控</div>
      </div>
      <a-table :dataSource="dataSource" :columns="columns" :pagination="false">
        <template #companyName="{ record }">
          <div class="data-name">
            <div class="icon-img">
              <img :src="record.logoUrl ? record.logoUrl : defaultIcon" alt="" />
            </div>
            {{ record.companyName }}
          </div>
        </template>
        <template #trends="{ record }">
          <div class="data-level">
            <div class="state-item item1">高风险 {{ record.highRiskCount }}</div>
            <div class="state-item item2">中风险 {{ record.middleRiskCount }}</div>
            <div class="state-item item3">低风险 {{ record.lowRiskCount }}</div>
            <div class="state-item item4">提示 {{ record.promptCount }}</div>
            <div class="state-item item5">正向 {{ record.positiveCount }}</div>
          </div>
        </template>
        <template #operation="{ record }">
          <!--          <a-popconfirm-->
          <!--            title="是否确定取消监控?"-->
          <!--            ok-text="是"-->
          <!--            cancel-text="否"-->
          <!--            @confirm="openDelBox(record.companyId)"-->
          <!--            @cancel="cancelDel"-->
          <!--          >-->
          <a style="color: #1473dc" @click="openDelBox(record.companyId)">取消监控</a>
          <!--          </a-popconfirm>-->
        </template>
      </a-table>
    </div>
    <div class="otherPagination">
      <div class="seizeASeat"> </div>
      <a-pagination
        size="small"
        :total="pageForm.total"
        :pageSize="pageForm.size"
        :current="pageForm.limit"
        :hideOnSinglePage="true"
        :showSizeChanger="false"
        @change="changePage"
        class="pag"
      />
    </div>
    <div style="clear: both"></div>
    <a-modal
      v-model:visible="isShowAdd"
      :maskClosable="false"
      :width="500"
      :centered="true"
      okText="确定"
      title="新增监控企业"
      @ok="saveData"
    >
      <a-form
        :model="addFormData"
        :label-col="{ span: 6 }"
        :wrapper-col="12"
        style="margin-top: 16px"
      >
        <a-form-item label="企业名称">
          <a-select
            v-model:value="addFormData.companyIds"
            mode="multiple"
            placeholder=""
            style="width: 300px"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            show-search
            @search="getSearchList"
          >
            <a-select-option :value="item.id" v-for="(item, index) in companyList" :key="index">
              <label v-html="item.companyName"></label>
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      v-model:visible="isShowUpload"
      :maskClosable="false"
      :width="600"
      :centered="true"
      :okText="titleContent"
      title="批量导入"
      @ok="saveUpload"
    >
      <div class="my-upload">
        <a-upload-dragger
          v-model:fileList="fileList"
          name="file"
          :multiple="true"
          action=""
          style="height: 500px"
          :beforeUpload="handleChange"
          :remove="removeFile"
        >
          <div class="ant-upload-hint" v-if="isUploadState === 0">
            <div class="upload-icon">
              <img src="../../../assets/images/upload.png" alt="" />
            </div>
            <div class="upload-click">
              <label style="color: #1473dc">点击选择</label
              ><label>或将文件（xls、xlsx）拖拽至此上传项目表格</label>
            </div>
          </div>
          <div class="ant-upload-hint" v-if="isUploadState === 1">
            <div class="upload-icon">
              <img src="../../../assets/images/success.png" alt="" />
            </div>
            <div class="upload-click" style="color: #303133"> 上传成功 </div>
          </div>
          <div class="ant-upload-hint" v-if="isUploadState === 2">
            <div class="upload-icon">
              <img src="../../../assets/images/error.png" alt="" />
            </div>
            <div class="upload-click" style="color: #303133"> 导入失败 </div>
            <div style="color: #909399">请使用标准导入模板进行数据导入，否则将无法导入成功</div>
          </div>
        </a-upload-dragger>
      </div>
      <div class="tips">
        <div class="tipsItem"
          >· 导入的文件内容必须依照下载模板的要求填写
          <div>
            <div class="downloadBtn">
              <img src="../../../assets/images/download.png" alt="" />
              <label @click="downloadData">点击下载</label>
            </div>
          </div></div
        >
        <div class="tipsItem">· 上传文件最大为2M，仅支持Excel表格文件（xls、xlsx）</div>
        <div class="tipsItem">· 导入重复数据将自动跳过</div>
      </div>
    </a-modal>
    <DeleteBox
      :is-show="isShowDelBox"
      :ok-text="'确认取消'"
      :cancel-text="'我再想想'"
      :prompt-text="'取消后将错过企业最新动态！'"
      @ok="returnOk"
      @cancel="isShowDelBox = false"
    />
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import PageTitle from '/@/components/PageTitle/index.vue';
  import { getCompanyList, removeCompany, saveCompany } from '/@/api/monitoringCenter';
  import { getTimes } from '/@/utils/index';
  import { message } from 'ant-design-vue';
  import { searchCompany } from '/@/api/supplierManage';
  import { downloadTemple } from '/@/api/fileApi';
  import { getAppEnvConfig } from '/@/utils/env';
  import DeleteBox from '/@/components/DeleteBox/index.vue';
  import defaultIcon from '/@/assets/images/defaultIcon.png';
  let isShowDelBox = ref(false);
  let delId = '';
  function openDelBox(id: string) {
    isShowDelBox.value = true;
    delId = id;
  }
  function returnOk() {
    isShowDelBox.value = false;
    cancleMonitor(delId);
  }
  let formData = ref({
    time: -1,
    times: [],
  });
  function changeTime() {
    pageForm.value.limit = 1;
    getList();
  }
  function resetData() {
    formData.value = {
      time: -1,
      times: [],
    };
    getList();
  }
  let dataSource = ref([]);
  let columns = ref([
    {
      title: '序号',
      align: 'left',
      dataIndex: 'index',
      key: 'index',
      // slots: { customRender: 'index' },
    },
    {
      title: '监控对象',
      dataIndex: 'companyName',
      align: 'left',
      key: 'companyName',
      slots: { customRender: 'companyName' },
    },
    {
      title: '风险动态',
      dataIndex: 'trends',
      align: 'left',
      key: 'trends',
      slots: { customRender: 'trends' },
    },
    {
      title: '监控日期',
      dataIndex: 'createTime',
      key: 'createTime',
      align: 'left',
    },
    {
      title: '查看',
      dataIndex: 'operation',
      key: 'operation',
      align: 'left',
      slots: { customRender: 'operation' },
    },
  ]);

  let pageForm = ref({
    size: 10,
    limit: 1,
    total: 0,
  });
  function changePage(val) {
    pageForm.value.limit = val;
    // todo
    getList();
  }
  async function getList() {
    let startTime = '';
    let endTime = '';
    if (formData.value.time === 0 && formData.value.times && formData.value.times.length === 2) {
      // 自定义日期
      startTime = formData.value.times[0];
      endTime = formData.value.times[1];
    } else {
      startTime = getTimes(formData.value.time)[0];
      endTime = getTimes(formData.value.time)[1];
    }
    let queryData = {
      limit: pageForm.value.limit,
      size: pageForm.value.size,
      startTime,
      endTime,
    };
    let res = await getCompanyList(queryData);
    let needCurrentPage = res.currentPage;
    dataSource.value = res.list.map((item, index) => {
      return {
        ...item,
        index: needCurrentPage * 10 - 10 + index + 1,
      };
    });
    pageForm.value.total = res.total;
  }
  getList();
  async function cancleMonitor(companyId: string) {
    await removeCompany({ companyId });
    getList();
  }
  function cancelDel() {
    message.info('已取消操作');
  }
  let addFormData = ref({
    companyIds: [],
  });
  let isShowAdd = ref(false);
  // 批量添加监控
  let isShowUpload = ref(false); // 是否打开批量监控弹窗
  function openUpload() {
    isShowUpload.value = true;
  }
  // 添加企业 打开弹窗
  function addCompany() {
    isShowAdd.value = true;
  }
  let companyList = ref([]);
  let timer = null;
  async function getSearchList(val: string) {
    if (!val || timer) {
      return;
    }
    let queryData = {
      limit: 1,
      size: 20,
      name: val,
    };
    const res = await searchCompany(queryData);
    companyList.value = res
      ? res.list.map((item) => {
          // item.label = item.companyName;
          // item.value = item.cid;
          return item;
        })
      : [];
    timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
    }, 200);
  }
  async function saveData() {
    let queryData = {
      companyIds: addFormData.value.companyIds,
    };
    if (queryData.companyIds.length === 0) {
      message.info('请选择企业');
      return;
    } else {
      const res = await saveCompany(queryData);
    }
    addFormData.value.companyIds = [];
    isShowAdd.value = false;
    getList();
  }
  let fileList = ref([]) as any;
  let titleContent = ref('确定导入');
  // 下载纪录
  async function downloadData() {
    let res = await downloadTemple('监控企业导入模板.xlsx');
    let url = window.URL.createObjectURL(res.data);
    let link = document.createElement('a');
    link.style.display = 'none';
    link.download = '监控企业导入模板.xlsx';
    link.href = url;
    document.body.appendChild(link);
    link.click();
  }
  let fileData = null;
  const handleChange = (file: any) => {
    fileData = file;
    fileList.value = [file];
    return false;
  };
  const removeFile = () => {
    fileList.value = [];
    fileData = null;
  };
  let isUploadState = ref(0);
  async function saveUpload() {
    if (!fileData) {
      return message.warn('请选择要上传的文件');
    }
    let action = getAppEnvConfig().VITE_GLOB_API_URL + '/company-monitor/company/import';
    const formData = new FormData();
    formData.append('file', fileData);
    const xhr = new XMLHttpRequest();
    xhr.open('post', action, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem('token'));
    xhr.onload = () => {
      const response = JSON.parse(xhr.response);
      if (response.code === 10500) {
        message.error('导入失败');
        titleContent.value = '重新上传';
        isUploadState.value = 2;
        fileData = null;
        fileList.value = [];
      } else {
        if (response.data === 'error') {
          message.warning(response.msg);
        } else {
          message.success('导入成功');
        }
        isUploadState.value = 1;
      }
    };
    xhr.onerror = () => {
      console.log('上传失败');
    };
    xhr.ontimeout = function timeout() {
      console.log('上传超时');
    };
    xhr.send(formData);
  }
</script>
<style lang="less" scoped>
  .enterpriseMonitoringList {
    .data-name {
      display: flex;
      width: 230px;
      .icon-img {
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin-right: 8px;
        img {
          width: 26px;
        }
      }
    }
    .data-level {
      display: flex;
      width: 400px;
      .state-item {
        padding: 0 10px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;
        text-align: center;
        border-radius: 2px;
        margin-right: 8px;
      }
      .item1 {
        border: 1px solid #da7679;
        color: #c11a20;
      }
      .item2 {
        border: 1px solid #e7a186;
        color: #c15a1a;
      }
      .item3 {
        border: 1px solid #efc16b;
        color: #e49708;
      }
      .item4 {
        border: 1px solid #72abea;
        color: #1473dc;
      }
      .item5 {
        border: 1px solid #73cf8f;
        color: #16af44;
      }
    }
    .addBtn {
      display: flex;
      margin-bottom: 16px;
      .btnItem {
        border: 1px solid #1473dc;
        width: 88px;
        height: 32px;
        border-radius: 4px;
        color: #1473dc;
        font-size: 14px;
        font-weight: 500;
        line-height: 32px;
        text-align: center;
        margin-right: 16px;
        cursor: pointer;
        &:active {
          opacity: 0.8;
        }
      }
    }
  }
  .my-upload {
    padding: 0 20px;
    margin-top: 32px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .upload-click {
      font-size: 14px;
    }
    img {
      margin: 0 auto;
    }
  }
  .tips {
    margin-top: 12px;
    padding: 0 20px;
    .tipsItem {
      font-size: 12px;
      font-weight: normal;
      line-height: 20px;
      letter-spacing: -0.01px;
      color: #606266;
      display: flex;
      .downloadBtn {
        width: fit-content;
        height: 24px;
        border-radius: 4px;
        display: flex;
        flex-direction: row;
        align-items: center;
        padding: 2px 8px;
        box-sizing: border-box;
        border: 1px solid #1473dc;
        margin-left: 8px;
        font-size: 12px;
        line-height: 24px;
        color: #1473dc;
        img {
          margin-right: 5px;
        }
      }
    }
  }
  .otherPagination {
    float: right !important;
    width: 100%;
    height: 32px;
    background-color: #fff !important;
    display: flex;
    flex-direction: row-reverse;
  }
  .myMybtn {
    margin-right: 22px;
    border-radius: 4px;
  }
</style>
